extends Node

## 玩家属性管理器
## 负责管理玩家的生命值、经验值、等级等属性

signal health_changed(current_hp: int, max_hp: int)
signal mana_changed(current_mp: int, max_mp: int)
signal experience_changed(current_exp: int, exp_to_next: int)
signal level_up(new_level: int)
signal player_died
signal gold_changed(current_gold: int)

# 玩家基础属性
var player_stats = {
	"level": 1,
	"max_hp": 120,
	"current_hp": 120,
	"max_mp": 50,  # 最大蓝量
	"current_mp": 50,  # 当前蓝量
	"base_attack": 25,  # 基础攻击力
	"defense": 12,
	"attack_speed": 100,
	"current_exp": 0,
	"exp_to_next": 100,
	"gold": 1000
}

# 等级成长参数
var level_growth = {
	"hp_per_level": 20,
	"mp_per_level": 10,  # 每级增加的蓝量
	"attack_per_level": 3,
	"defense_per_level": 2,
	"attack_speed_per_level": 5,
	"exp_multiplier": 1.5
}

# 装备加成
var equipment_bonus = {
	"attack": 0,
	"defense": 0,
	"hp": 0,
	"mp": 0  # 蓝量加成
}

# 标记是否正在加载存档数据
var _is_loading_save_data = false

func get_total_attack() -> int:
	"""获取总攻击力（基础攻击力 + 装备加成）"""
	return player_stats.base_attack + equipment_bonus.attack

func update_equipment_bonus():
	"""更新装备加成属性"""
	if ItemManager == null:
		return
	
	var equipment_stats = ItemManager.get_total_equipment_stats()
	
	# 计算攻击力加成（基于力量属性）
	equipment_bonus.attack = equipment_stats.strength
	
	# 计算防御力加成
	equipment_bonus.defense = equipment_stats.physical_defense
	
	# 计算生命值加成（基于耐力属性）
	equipment_bonus.hp = equipment_stats.stamina * 5  # 每点耐力增加5点生命值
	
	# 计算蓝量加成（基于智力属性）
	equipment_bonus.mp = equipment_stats.get("intelligence", 0) * 3  # 每点智力增加3点蓝量
	
	# 计算基础最大生命值（1级时的基础值 + 等级成长）
	var base_max_hp = 120 + (player_stats.level - 1) * level_growth.hp_per_level
	var new_max_hp = base_max_hp + equipment_bonus.hp
	player_stats.max_hp = new_max_hp
	
	# 计算基础最大蓝量（1级时的基础值 + 等级成长）
	var base_max_mp = 50 + (player_stats.level - 1) * level_growth.mp_per_level
	var new_max_mp = base_max_mp + equipment_bonus.mp
	player_stats.max_mp = new_max_mp
	
	print("[DEBUG] update_equipment_bonus - 加载存档标记: ", _is_loading_save_data)
	print("[DEBUG] update_equipment_bonus - 更新前生命值: ", player_stats.current_hp, "/", player_stats.max_hp)
	print("[DEBUG] update_equipment_bonus - 更新前蓝量: ", player_stats.current_mp, "/", player_stats.max_mp)
	
	# 只有在非加载存档状态下才限制当前生命值和蓝量
	if not _is_loading_save_data:
		print("[DEBUG] update_equipment_bonus - 限制生命值和蓝量")
		# 装备变化时不增加当前生命值，只更新最大值
		# 确保当前生命值不超过新的最大值
		player_stats.current_hp = min(player_stats.current_hp, player_stats.max_hp)
		
		# 装备变化时不增加当前蓝量，只更新最大值
		# 确保当前蓝量不超过新的最大值
		player_stats.current_mp = min(player_stats.current_mp, player_stats.max_mp)
	else:
		print("[DEBUG] update_equipment_bonus - 跳过限制（正在加载存档）")
	
	print("[DEBUG] update_equipment_bonus - 更新后生命值: ", player_stats.current_hp, "/", player_stats.max_hp)
	print("[DEBUG] update_equipment_bonus - 更新后蓝量: ", player_stats.current_mp, "/", player_stats.max_mp)
	
	health_changed.emit(player_stats.current_hp, player_stats.max_hp)
	mana_changed.emit(player_stats.current_mp, player_stats.max_mp)

func get_total_defense() -> int:
	"""获取总防御力（基础防御力 + 装备加成）"""
	return player_stats.defense + equipment_bonus.defense

# 生命恢复参数
var health_regen = {
	"steps_per_heal": 5,
	"heal_percentage": 0.02,  # 恢复最大生命值的2%
	"current_steps": 0
}

func _ready():
	process_mode = Node.PROCESS_MODE_ALWAYS
	# 初始化时发送信号
	health_changed.emit(player_stats.current_hp, player_stats.max_hp)
	mana_changed.emit(player_stats.current_mp, player_stats.max_mp)
	experience_changed.emit(player_stats.current_exp, player_stats.exp_to_next)
	gold_changed.emit(player_stats.gold)
	
	# 等待一帧后连接ItemManager和PhantomBeastManager信号
	await get_tree().process_frame
	if ItemManager != null:
		ItemManager.equipment_changed.connect(_on_equipment_changed)
		update_equipment_bonus()  # 初始化装备加成
	
	if PhantomBeastManager != null:
		PhantomBeastManager.formation_changed.connect(_on_formation_changed)
		

func _on_equipment_changed(_slot, _equipment):
	"""装备变化时更新装备加成"""
	update_equipment_bonus()

func _on_formation_changed(_active_beasts: Array[Dictionary]):
	"""幻兽队伍变化处理"""
	pass

func get_player_battle_data() -> Dictionary:
	"""获取玩家战斗数据"""
	return {
		"name": "勇者",
		"max_hp": player_stats.max_hp,
		"current_hp": player_stats.current_hp,
		"max_mp": player_stats.max_mp,
		"current_mp": player_stats.current_mp,
		"attack": get_total_attack(),
		"defense": get_total_defense(),
		"attack_speed": player_stats.attack_speed,
		"level": player_stats.level
	}

func update_player_hp_after_battle(new_hp: int):
	"""战斗后更新玩家生命值"""
	player_stats.current_hp = max(0, min(new_hp, player_stats.max_hp))
	health_changed.emit(player_stats.current_hp, player_stats.max_hp)
	
	if player_stats.current_hp <= 0:
		player_died.emit()

func gain_experience(exp_amount: int):
	"""获得经验值"""
	player_stats.current_exp += exp_amount
	
	# 检查是否升级
	while player_stats.current_exp >= player_stats.exp_to_next:
		level_up_player()
	
	experience_changed.emit(player_stats.current_exp, player_stats.exp_to_next)

func level_up_player():
	"""玩家升级"""
	player_stats.current_exp -= player_stats.exp_to_next
	player_stats.level += 1
	
	# 提升属性
	player_stats.max_hp += level_growth.hp_per_level
	player_stats.max_mp += level_growth.mp_per_level
	player_stats.base_attack += level_growth.attack_per_level
	player_stats.defense += level_growth.defense_per_level
	player_stats.attack_speed += level_growth.attack_speed_per_level
	
	# 升级时恢复30%的最大生命值和蓝量
	var heal_amount = int(player_stats.max_hp * 0.3)
	var mana_amount = int(player_stats.max_mp * 0.3)
	player_stats.current_hp = min(player_stats.current_hp + heal_amount, player_stats.max_hp)
	player_stats.current_mp = min(player_stats.current_mp + mana_amount, player_stats.max_mp)
	
	# 计算下一级所需经验
	player_stats.exp_to_next = int(player_stats.exp_to_next * level_growth.exp_multiplier)
	
	level_up.emit(player_stats.level)
	health_changed.emit(player_stats.current_hp, player_stats.max_hp)
	mana_changed.emit(player_stats.current_mp, player_stats.max_mp)

func heal_on_walk():
	"""行走时恢复生命值"""
	health_regen.current_steps += 1
	
	if health_regen.current_steps >= health_regen.steps_per_heal:
		health_regen.current_steps = 0
		
		# 恢复玩家生命值（按最大生命值百分比恢复）
		if player_stats.current_hp < player_stats.max_hp:
			var heal_amount = max(1, int(player_stats.max_hp * health_regen.heal_percentage))  # 至少恢复1点
			player_stats.current_hp = min(
				player_stats.current_hp + heal_amount,
				player_stats.max_hp
			)
			health_changed.emit(player_stats.current_hp, player_stats.max_hp)
		
		# 恢复上阵幻兽的生命值
		if PhantomBeastManager != null:
			PhantomBeastManager.heal_formation_on_walk()

func get_current_hp() -> int:
	return player_stats.current_hp

func get_max_hp() -> int:
	return player_stats.max_hp

func get_current_exp() -> int:
	return player_stats.current_exp

func get_exp_to_next() -> int:
	return player_stats.exp_to_next

func get_level() -> int:
	return player_stats.level

func is_alive() -> bool:
	return player_stats.current_hp > 0

func heal_to_full():
	"""完全恢复生命值"""
	player_stats.current_hp = player_stats.max_hp
	health_changed.emit(player_stats.current_hp, player_stats.max_hp)

func take_damage(damage: int):
	"""受到伤害"""
	player_stats.current_hp = max(0, player_stats.current_hp - damage)
	health_changed.emit(player_stats.current_hp, player_stats.max_hp)
	
	if player_stats.current_hp <= 0:
		player_died.emit()

func save_stats_data() -> Dictionary:
	"""保存属性数据"""
	return player_stats.duplicate()

func load_stats_data(data: Dictionary):
	"""加载属性数据"""
	# 保存当前生命值，用于后续恢复
	var saved_current_hp = data.get("current_hp", player_stats.current_hp)
	var saved_current_mp = data.get("current_mp", player_stats.current_mp)
	
	print("[DEBUG] 加载存档 - 存档中的生命值: ", saved_current_hp, "/", data.get("max_hp", player_stats.max_hp))
	print("[DEBUG] 加载存档 - 存档中的蓝量: ", saved_current_mp, "/", data.get("max_mp", player_stats.max_mp))
	
	for key in data.keys():
		if player_stats.has(key):
			player_stats[key] = data[key]
	
	print("[DEBUG] 加载数据后 - 当前生命值: ", player_stats.current_hp, "/", player_stats.max_hp)
	print("[DEBUG] 加载数据后 - 当前蓝量: ", player_stats.current_mp, "/", player_stats.max_mp)
	
	# 设置加载存档标记
	_is_loading_save_data = true
	
	# 加载数据后更新装备加成
	update_equipment_bonus()
	
	print("[DEBUG] 装备加成更新后 - 当前生命值: ", player_stats.current_hp, "/", player_stats.max_hp)
	print("[DEBUG] 装备加成更新后 - 当前蓝量: ", player_stats.current_mp, "/", player_stats.max_mp)
	
	# 恢复存档中的实际生命值和蓝量，不受装备加成限制影响
	player_stats.current_hp = saved_current_hp
	player_stats.current_mp = saved_current_mp
	
	print("[DEBUG] 恢复存档值后 - 当前生命值: ", player_stats.current_hp, "/", player_stats.max_hp)
	print("[DEBUG] 恢复存档值后 - 当前蓝量: ", player_stats.current_mp, "/", player_stats.max_mp)
	
	# 清除加载存档标记
	_is_loading_save_data = false
	
	health_changed.emit(player_stats.current_hp, player_stats.max_hp)
	mana_changed.emit(player_stats.current_mp, player_stats.max_mp)
	experience_changed.emit(player_stats.current_exp, player_stats.exp_to_next)
	gold_changed.emit(player_stats.gold)

func lose_experience_on_defeat():
	"""被击败时损失5%的经验值"""
	var exp_loss = int(player_stats.current_exp * 0.05)
	player_stats.current_exp = max(0, player_stats.current_exp - exp_loss)
	experience_changed.emit(player_stats.current_exp, player_stats.exp_to_next)
	print("被击败损失经验值: ", exp_loss)

func get_gold() -> int:
	"""获取当前金币数量"""
	return player_stats.gold

func add_gold(amount: int):
	"""增加金币"""
	player_stats.gold += amount
	gold_changed.emit(player_stats.gold)

func spend_gold(amount: int) -> bool:
	"""消费金币，返回是否成功"""
	if player_stats.gold >= amount:
		player_stats.gold -= amount
		gold_changed.emit(player_stats.gold)
		return true
	return false

# 蓝量管理方法
func get_current_mp() -> int:
	"""获取当前蓝量"""
	return player_stats.current_mp

func get_max_mp() -> int:
	"""获取最大蓝量"""
	return player_stats.max_mp

func consume_mp(amount: int) -> bool:
	"""消耗蓝量，返回是否成功"""
	if player_stats.current_mp >= amount:
		player_stats.current_mp -= amount
		mana_changed.emit(player_stats.current_mp, player_stats.max_mp)
		return true
	return false

func restore_mp(amount: int):
	"""恢复蓝量"""
	player_stats.current_mp = min(player_stats.current_mp + amount, player_stats.max_mp)
	mana_changed.emit(player_stats.current_mp, player_stats.max_mp)

func restore_mp_full():
	"""完全恢复蓝量"""
	player_stats.current_mp = player_stats.max_mp
	mana_changed.emit(player_stats.current_mp, player_stats.max_mp)

func get_mp_percentage() -> float:
	"""获取蓝量百分比"""
	if player_stats.max_mp <= 0:
		return 0.0
	return float(player_stats.current_mp) / float(player_stats.max_mp)

func heal(amount: int):
	"""恢复生命值"""
	player_stats.current_hp = min(player_stats.current_hp + amount, player_stats.max_hp)
	health_changed.emit(player_stats.current_hp, player_stats.max_hp)

func add_experience(exp_amount: int):
	"""增加经验值（兼容性函数，调用gain_experience）"""
	gain_experience(exp_amount)

func heal_full():
	"""完全恢复生命值（兼容性函数，调用heal_to_full）"""
	heal_to_full()
